package com.zz.nondatain.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.GridLayout;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.zz.nondatain.R;
import com.zz.nondatain.base.BaseActivity;
import com.zz.nondatain.databinding.ActivityActiveSignInBinding;
import com.zz.nondatain.databinding.ActivityAttendanceCalendarBinding;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

/**
 * 考勤月历页面，显示月度考勤情况
 */
public class AttendanceCalendarActivity extends BaseActivity<ActivityAttendanceCalendarBinding> {

    private Calendar currentCalendar;
    private int selectedDay = -1;
    private TextView[] dayViews;
    private TextView[] statusViews;
    
    // 模拟的考勤数据（实际应从服务器获取）
    private static final int STATUS_NORMAL = 0;  // 正常打卡
    private static final int STATUS_MISSED = 1;  // 缺卡
    private static final int STATUS_NORMAL_OUT = 2;  // 越界

    protected void initView() {
        currentCalendar = Calendar.getInstance();
        // 设置标题
        SimpleDateFormat yearMonthFormat = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
        String yearMonth = yearMonthFormat.format(currentCalendar.getTime());
        binding.tvTitle.setText("考勤月历 " + yearMonth);
        
        // 设置用户信息
        binding.tvUserName.setText("张膨山1");
        binding.tvUserId.setText("编号：13010220240100001");
        
        // 设置当前日期和星期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        SimpleDateFormat weekdayFormat = new SimpleDateFormat("EEEE", Locale.CHINESE);
        String currentDate = dateFormat.format(new Date());
        String weekday = weekdayFormat.format(new Date());
        binding.tvCurrentDate.setText(currentDate + " " + weekday);
        
        // 设置底部统计信息
        updateAttendanceSummary();
    }

    @Override
    protected void initData() {
        setupListeners();
        updateCalendar();
    }

    @Override
    protected void initObservers() {

    }

    @Override
    protected ActivityAttendanceCalendarBinding getViewBinding() {
        return ActivityAttendanceCalendarBinding.inflate(getLayoutInflater());
    }

    private void setupListeners() {
        // 返回按钮点击事件
        binding.btnBack.setOnClickListener(v -> finish());
        
        // 考勤汇总按钮点击事件
        binding.btnAttendanceSummary.setOnClickListener(v -> {
            // 跳转到考勤统计页面
            Intent intent = new Intent(this, AttendanceStatsActivity.class);
            startActivity(intent);
        });
    }
    
    private void updateCalendar() {
        // 获取当前月份的天数
        int daysInMonth = currentCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        
        // 获取当前月的第一天是星期几
        Calendar firstDayOfMonth = (Calendar) currentCalendar.clone();
        firstDayOfMonth.set(Calendar.DAY_OF_MONTH, 1);
        int firstDayOfWeek = firstDayOfMonth.get(Calendar.DAY_OF_WEEK) - 1; // 星期日是1，我们需要从0开始
        
        // 清除日历网格
        binding.calendarGrid.removeAllViews();
        
        // 准备日历视图数组
        dayViews = new TextView[42]; // 6行7列
        statusViews = new TextView[42];
        
        // 填充星期标题
        String[] weekdays = {"日", "一", "二", "三", "四", "五", "六"};
        for (int i = 0; i < 7; i++) {
            TextView weekdayView = new TextView(this);
            weekdayView.setText(weekdays[i]);
            weekdayView.setTextColor(getResources().getColor(android.R.color.darker_gray));
            weekdayView.setTextSize(14);
            weekdayView.setPadding(0, 16, 0, 16);
            weekdayView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.width = 0;
            params.height = GridLayout.LayoutParams.WRAP_CONTENT;
            params.columnSpec = GridLayout.spec(i, 1, 1f);
            params.rowSpec = GridLayout.spec(0);
            binding.calendarGrid.addView(weekdayView, params);
        }
        
        // 填充日期和状态
        Random random = new Random();
        Calendar today = Calendar.getInstance();
        int currentDay = today.get(Calendar.DAY_OF_MONTH);
        boolean isSameMonth = today.get(Calendar.YEAR) == currentCalendar.get(Calendar.YEAR) 
                && today.get(Calendar.MONTH) == currentCalendar.get(Calendar.MONTH);
        
        for (int i = 0; i < 42; i++) {
            int row = i / 7 + 1; // +1因为第一行是星期标题
            int col = i % 7;
            int day = i - firstDayOfWeek + 1;
            
            // 创建日期容器
            LinearLayout dayContainer = new LinearLayout(this);
            dayContainer.setOrientation(LinearLayout.VERTICAL);
            dayContainer.setBackgroundResource(android.R.color.transparent);
            
            // 创建日期文本视图
            TextView dayView = new TextView(this);
            if (day > 0 && day <= daysInMonth) {
                dayView.setText(String.valueOf(day));
                dayView.setTextSize(16);
                
                // 高亮当天
                if (isSameMonth && day == currentDay) {
                    dayView.setBackgroundResource(R.drawable.circle_button_background);
                    dayView.setTextColor(getResources().getColor(android.R.color.white));
                    selectedDay = day;
                } else {
                    dayView.setBackgroundResource(android.R.color.transparent);
                    dayView.setTextColor(getResources().getColor(android.R.color.black));
                }
                
                final int dayFinal = day;
                dayView.setOnClickListener(v -> {
                    if (selectedDay != -1 && dayViews[selectedDay - 1 + firstDayOfWeek] != null) {
                        // 取消之前选中的日期高亮
                        dayViews[selectedDay - 1 + firstDayOfWeek].setBackgroundResource(android.R.color.transparent);
                        dayViews[selectedDay - 1 + firstDayOfWeek].setTextColor(getResources().getColor(android.R.color.black));
                    }
                    
                    // 高亮新选中的日期
                    selectedDay = dayFinal;
                    dayView.setBackgroundResource(R.drawable.circle_button_background);
                    dayView.setTextColor(getResources().getColor(android.R.color.white));
                    
                    // 更新底部考勤详情
                    updateDailyAttendanceDetails(dayFinal);
                });
                
                // 保存日期视图引用
                dayViews[i] = dayView;
                
                // 添加状态标签
                TextView statusView = new TextView(this);
                // 随机状态，实际应从数据库或API获取
                int status = random.nextInt(3);
                
                switch (status) {
                    case STATUS_NORMAL:
                        statusView.setText("正常");
                        statusView.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
                        break;
                    case STATUS_MISSED:
                        statusView.setText("未打卡");
                        statusView.setTextColor(getResources().getColor(android.R.color.holo_orange_dark));
                        break;
                    case STATUS_NORMAL_OUT:
                        statusView.setText("越界");
                        statusView.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                        break;
                }
                
                statusView.setTextSize(10);
                statusView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                statusViews[i] = statusView;
            } else {
                // 空白日期
                dayView.setText("");
                dayView.setClickable(false);
            }
            
            dayView.setPadding(0, 8, 0, 4);
            dayView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            
            // 添加日期和状态到容器
            dayContainer.addView(dayView);
            if (day > 0 && day <= daysInMonth) {
                dayContainer.addView(statusViews[i]);
            }
            
            // 添加容器到网格
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.width = 0;
            params.height = GridLayout.LayoutParams.WRAP_CONTENT;
            params.columnSpec = GridLayout.spec(col, 1, 1f);
            params.rowSpec = GridLayout.spec(row);
            binding.calendarGrid.addView(dayContainer, params);
        }
        
        // 如果有选中的日期，更新详情
        if (selectedDay != -1) {
            updateDailyAttendanceDetails(selectedDay);
        }
    }
    
    private void updateAttendanceSummary() {
        // 模拟数据，实际应从API获取
        int normalCount = 10;
        int missedCount = 2;
        int outOfBoundsCount = 1;
        
        binding.tvAttendanceSummary.setText(
                String.format("今日正常打卡%d次 缺卡%d次 越界%d次",
                        normalCount, missedCount, outOfBoundsCount));
    }
    
    private void updateDailyAttendanceDetails(int day) {
        // 基于选中的日期生成详情（模拟数据）
        Random random = new Random();
        int status = random.nextInt(2); // 0: 正常打卡, 1: 缺卡
        
        binding.layoutDailyDetails.setVisibility(View.VISIBLE);
        
        if (status == 0) { // 正常打卡
            binding.tvAttendanceStatus.setText("正常");
            binding.tvAttendanceStatus.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
            binding.tvCheckInTime.setVisibility(View.VISIBLE);
            binding.tvCheckInLocation.setVisibility(View.VISIBLE);
            
            // 模拟签到时间和地点
            binding.tvCheckInTime.setText("签到时间：08:30:25");
            binding.tvCheckInLocation.setText("签到地点：中国四川省成都市武侯区武兴五路433号2栋西部智谷");
        } else { // 缺卡
            binding.tvAttendanceStatus.setText("缺卡");
            binding.tvAttendanceStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
            binding.tvCheckInTime.setVisibility(View.GONE);
            binding.tvCheckInLocation.setVisibility(View.GONE);
        }
        
        binding.tvAttendanceRange.setText("考勤范围：00:00:00-23:30:00");
    }
} 